package com.slh.flutter_phone;

import android.app.Activity;
import android.content.pm.PackageManager;
import android.text.TextUtils;

import androidx.annotation.NonNull;

import com.slh.flutter_phone.utils.PhoneUtils;

import org.json.JSONException;

import java.lang.reflect.Method;
import java.util.Map;

import io.flutter.Log;
import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.embedding.engine.plugins.activity.ActivityAware;
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
import io.flutter.plugin.common.EventChannel;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugin.common.PluginRegistry;

/**
 * FlutterPhonePlugin
 */
public class FlutterPhonePlugin implements FlutterPlugin, MethodCallHandler, ActivityAware, PluginRegistry.RequestPermissionsResultListener {
    /// The MethodChannel that will the communication between Flutter and native Android
    ///
    /// This local reference serves to register the plugin with the Flutter Engine and unregister it
    /// when the Flutter Engine is detached from the Activity
    private MethodChannel channel;
    private EventChannel _channelEvent;
    public static EventChannel.EventSink EVENT_SINK;
    public static Result RESULT;

    @Override
    public boolean onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        Log.e("权限回调", "成功" + requestCode);
        if (requestCode == PhoneUtils.READ_PHONE_STATE_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                try {
                    PhoneUtils.simInfo();
                } catch (JSONException e) {
                    e.printStackTrace();
                    RESULT.success("{}");
                }
            }
        }

        if (requestCode == PhoneUtils.READ_CONTACTS_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                try {
                    PhoneUtils.getContacts(PhoneUtils.PAGE_SIZE, 1);
                } catch (JSONException e) {
                    e.printStackTrace();
                    RESULT.success("{\"total\":0,\"list\":[]}");
                }
            }
        }
        if (requestCode == PhoneUtils.READ_CALL_LOG_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                try {
                    PhoneUtils.getAllCallRecords();
                } catch (JSONException e) {
                    e.printStackTrace();
                    RESULT.success("{\"total\":0,\"list\":[]}");
                }
            }
        }
        if (requestCode == PhoneUtils.EXTERNAL_STORAGE_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                PhoneUtils.getCallRecordsAudioByPhoneNumber(PhoneUtils.PHONE_NUMBER);
            }
        }

        return false;
    }


    @Override
    public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
        channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "flutter_phone");
        channel.setMethodCallHandler(this);
        _channelEvent = new EventChannel(flutterPluginBinding.getBinaryMessenger(), "flutter_phone_event");
        _channelEvent.setStreamHandler(new EventChannel.StreamHandler() {
            @Override
            public void onListen(Object arguments, EventChannel.EventSink events) {
                EVENT_SINK = events;
            }

            @Override
            public void onCancel(Object arguments) {

            }
        });

    }

    @Override
    public synchronized void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
        RESULT = result;
        Map<String, Object> map = call.arguments();
        if (call.method.equals("call")) {
            //拨打电话
            String phoneNumber = map.get("phoneNumber").toString();
            boolean isDirect = Boolean.parseBoolean(map.get("isDirect").toString());
            int slotIndex = Integer.parseInt(map.get("slotIndex").toString());
            PhoneUtils.call(phoneNumber, isDirect, slotIndex);
        } else if (call.method.equals("simInfo")) {
            //获取单个号码的通话记录
            try {
                PhoneUtils.simInfo();
            } catch (JSONException e) {
                e.printStackTrace();
                RESULT.success("{}");
            }
        } else if (call.method.equals("getCallRecordsAudioByPhoneNumber")) {
            //获取单个号码的通话记录
            String phoneNumber = map.get("phoneNumber").toString();
            PhoneUtils.getCallRecordsAudioByPhoneNumber(phoneNumber);
        } else if (call.method.equals("getAllCallRecords")) {
            //获取通话记录列表
            try {
                PhoneUtils.getAllCallRecords();
            } catch (JSONException e) {
                e.printStackTrace();
                RESULT.success("{\"total\":0,\"list\":[]}");
            }
        } else if (call.method.equals("getContacts")) {
            //获取单个号码的通话记录
            int page = Integer.parseInt(map.get("page").toString());
            int pageSize = Integer.parseInt(map.get("pageSize").toString());
            try {
                PhoneUtils.getContacts(pageSize, page);
            } catch (JSONException e) {
                e.printStackTrace();
                RESULT.success("{\"total\":0,\"list\":[]}");
            }
        } else if (call.method.equals("isHarmonyOs")) {
            RESULT.success(isHarmonyOs());
        } else if (call.method.equals("getHarmonyVersion")) {
            RESULT.success(getHarmonyVersion());
        } else {
            result.notImplemented();
        }
    }

    @Override
    public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {

        channel.setMethodCallHandler(null);
        _channelEvent.setStreamHandler(null);
    }

    @Override
    public void onAttachedToActivity(@NonNull ActivityPluginBinding binding) {
        binding.addRequestPermissionsResultListener(this);
        PhoneUtils.init(binding.getActivity());

    }

    @Override
    public void onDetachedFromActivityForConfigChanges() {

    }

    @Override
    public void onReattachedToActivityForConfigChanges(@NonNull ActivityPluginBinding binding) {

    }

    @Override
    public void onDetachedFromActivity() {
        PhoneUtils.destroy();
    }

    /**
     * 是否为鸿蒙系统
     *
     * @return true为鸿蒙系统
     */
    public static boolean isHarmonyOs() {
        try {
            Class<?> buildExClass = Class.forName("com.huawei.system.BuildEx");
            Object osBrand = buildExClass.getMethod("getOsBrand").invoke(buildExClass);
            return "Harmony".equalsIgnoreCase(osBrand.toString());
        } catch (Throwable x) {
            return false;
        }
    }

    /**
     * 获取鸿蒙系统版本号
     *
     * @return 版本号
     */
    public static String getHarmonyVersion() {
        return getProp("hw_sc.build.platform.version", "");
    }

    private static String getProp(String property, String defaultValue) {
        try {
            Class spClz = Class.forName("android.os.SystemProperties");
            Method method = spClz.getDeclaredMethod("get", String.class);
            String value = (String) method.invoke(spClz, property);
            if (TextUtils.isEmpty(value)) {
                return defaultValue;
            }
            return value;
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return defaultValue;
    }
}
